var http = require('http');
var url = require("url"),
  path = require("path"),
  fs = require("fs");
var util = require("util"),
    mime = require("./mime").types;
//  routes
var routers = [],
  _static = {},
  config = {
    overwirte: true,
    listenPort: process.env.VCAP_APP_PORT || 3000
  };
var get = function(path, cbk) {
  routers.push({
    path: path,
    output: function(req, res) {
      res.writeHead(200, {
        'Content-Type': 'text/plain;charset=utf-8'
      });
      cbk(req, res);
    }
  });
};
var use_static = function(_path) {

    _static[_path] = true;  
  
};
var set = function(key, value) {
  var write = true;
  config[k] && !config.overwirte ? wirte = false : null;
  write ? config[key] = value : null;
};
var start = function() {
  http.createServer(function(request, response) {

    var uri = url.parse(request.url).pathname;
    var filename = path.join(process.cwd(), uri);
    var lookup = decodeURI(request.url);
    //判断是否为静态文件
    if (isStatic(lookup)) {
       response.writeHead(500, {
        "Content-Type": "text/plain"
      });
      response.write("\n");
      response.end();
      return;
    }
    //路由
    routers.forEach(function(route) {
      var isMatch = util.isRegExp(route.path) ? route.path.test(lookup) : route.path === lookup;
      //find a match route
      if (isMatch) {
        if (typeof route.output === 'function') {
          route.output(request, response);
          response.end();
        } else {
          response.writeHead(200, {
            'Content-Type': 'text/html;charset=utf-8'
          });
          response.end(route.output);
        }
      }
    });

    path.exists(filename, function(exists) {
      if (!exists) {
        response.writeHead(404, {
          "Content-Type": "text/plain"
        });
        response.write("404 Not Found\n");
        response.end();
        return;
      }

      if (fs.statSync(filename).isDirectory()) filename += './index.html';
      //读&&写
      read_write(filename,null, response);
    });
  }).listen(config.listenPort, null);
  console.log("server is start at " + config.listenPort + " port");
}

function isStatic(lookup) {
  for (var k in _static) {
    return new RegExp("^" + k).test(lookup);
  }
}

function read_write(filename,contentType, response) {
  fs.readFile(filename, "binary", function(err, file) {
    if (err) {
      response.writeHead(500, {
        "Content-Type": "text/plain"
      });
      response.write(err + "\n");
      response.end();
      return;
    }

    response.writeHead(200,{
      "contentType" : contentType ||"text/plain"
    });
    response.write(file, "binary");
    response.end();
  });
}

use_static("/server");
use_static("/apps");
module.exports = {
  start: start,
  get: get,
  set: set,
  use_static: use_static
}